package com.ushine.web.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ushine.web.base.mapper.UserGroupAndRoleMapper;
import com.ushine.web.base.model.relation.UserGroupAndRoleDO;
import com.ushine.web.base.service.IUserGroupAndRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: yls
 * @Date: 2022/02/15 23:48
 * @Description: 权限和用户组关联
 * @Version 1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserGroupAndRoleServiceImpl extends ServiceImpl<UserGroupAndRoleMapper, UserGroupAndRoleDO>
        implements IUserGroupAndRoleService {


    @Override
    public Boolean insertBatchUserGroupAndRoles(List<UserGroupAndRoleDO> roleAndUserGroups) {
        Set<Long> userGroupIds = roleAndUserGroups.stream().map(UserGroupAndRoleDO::getUserGroupId).collect(Collectors.toSet());
        LambdaQueryWrapper<UserGroupAndRoleDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(UserGroupAndRoleDO::getUserGroupId, userGroupIds);
        remove(lambdaQueryWrapper);
        return saveBatch(roleAndUserGroups);
    }

    @Override
    @Transactional(readOnly = true)
    public List<UserGroupAndRoleDO> listUserGroupAndRoles(Long userGroupId) {
        LambdaQueryWrapper<UserGroupAndRoleDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserGroupAndRoleDO::getUserGroupId, userGroupId)
                .select(UserGroupAndRoleDO::getRoleId);
        return Optional.ofNullable(list(lambdaQueryWrapper)).orElse(new ArrayList<>(0));
    }
}
